<template>
  <a-modal :open="open" width="840px" destroy-on-close centered :footer="null" @cancel="onCancel">
    <template #title>
      <div class="flex items-start pr-20">
        <span class="w-[130px]">{{ actionType === 0 ? '医保登记' : '医保退号' }} </span>
        <a-radio-group v-model:value="tabActiveKey" button-style="solid" size="large" class="flex-1 -mt-2 flex justify-center" @change="onTabRadioChange">
          <a-radio-button v-for="(item, index) in filterType()" :key="index" :value="item.name">{{ item.name }}</a-radio-button>
        </a-radio-group>
      </div>
    </template>
    <div class="bg-secondary w-full p-4 rounded-md border border-solid border-primary">
      <div class="flex items-end justify-between">
        <div class="flex items-end w-1/4">
          <div class="text-lg font-semibold text-primary">{{ formState?.brName }}</div>
          <div class="mx-3">{{ formState?.brXb }}</div>
          <div>{{ formState?.brAge || '-' }}</div>
        </div>
        <div class="w-[45%]">
          <LabelValue label="挂号时间" :width="240" :value="formState?.ghsj" />
        </div>
        <div class="w-[30%]">
          <LabelValue label="就诊编号" class="!w-full" :value="formState?.jzbh" />
        </div>
      </div>
      <div class="flex items-center mt-4 justify-between">
        <div class="w-1/4">
          <LabelValue label="挂号类别" :value="formState?.ghlb" />
        </div>
        <div class="w-1/4">
          <LabelValue label="挂号科室" :value="formState?.ksmc" />
        </div>
        <div class="w-1/5">
          <LabelValue label="挂号医生" :value="formState?.empName" />
        </div>
        <div class="w-[30%]">
          <LabelValue label="病历卡号" class="!w-full" :value="formState?.brBlkh" />
        </div>
      </div>
    </div>
    <div class="flex justify-between p-4">
      <div class="mt-5 mb-5 flex-1">
        <div class="flex justify-end mb-3">
          <a-input
            v-if="tabActiveKey === '电子凭证'"
            v-model:value="formState.ck"
            placeholder="请扫描电子凭证"
            class="w-[360px]"
            @keyup.enter="readYbSrzCard(false)"
          />
          <a-input v-if="tabActiveKey === '磁卡'" v-model:value="formState.ck" placeholder="请刷磁卡" class="w-[360px]" @keyup.enter="readYbSrzCard(false)" />
          <div class="flex flex-1 justify-end items-center">
            <a-button class="" type="primary" @click="readYbSrzCard(false)">读卡</a-button>
            <a-input v-if="inAreaCode === '02' && tabActiveKey === '身份证'" v-model:value="idNumber" class="w-[200px] ml-2" placeholder="请输入身份证号" />
            <a-button v-if="inAreaCode === '02' && tabActiveKey === '身份证'" class="ml-2" type="primary" @click="readYbSrzCard(true)">读卡</a-button>
          </div>
        </div>
        <div class="flex">
          <div class="w-[400px]">
            <LabelValue label="社保卡号" class="mb-2 font-bold" tooltip :width="260" :value="medFormState?.insureNo" />
            <LabelValue label="身份证号" class="mb-2" :width="260" tooltip :value="medFormState?.sfzh" />
            <!-- <LabelValue label-class="w-[110px]" label="就诊凭证编号" class="mb-2" tooltip :width="300" :value="medFormState?.mdtrtCertNo" /> -->
            <div class="flex items-center mb-2">
              <div class="w-[80px]">险种类别：</div>
              <a-input v-model:value="checkInsutypeName.insutypeName" class="w-[230px]" placeholder="险种类别" allow-clear @click="onClickInsutypeName(true)" />
            </div>
            <div class="flex items-center">
              <div class="w-[80px] relative"><span class="text-red-500 absolute top-0 -left-2">*</span> 医疗类别：</div>
              <SelectItem
                v-model:value="formState.med_type"
                class="w-[230px]"
                select-first
                type="med_type"
                :params="{ type: '门诊' }"
                trigger="init"
                placeholder="请选择"
              />
            </div>
          </div>
          <div class="w-1/2">
            <LabelValue label="卡识别码" class="mb-2" tooltip :width="380" :value="medFormState?.ksbm_new" />
          </div>
        </div>
      </div>
      <!-- v-if="tabActiveKey !== '04' && tabActiveKey !== '05'" -->

      <!-- 账户查询五期 -->
      <AccountQueryFive v-model:open="accountQueryFiveOpen" :resource-data="accountQueryData" />
      <!-- 账户查询六期 -->
      <AccountQuerySix v-model:open="accountQuerySixOpen" :resource-data="accountQueryData" :select="checkInsutypeName" @ok="onSelectCHS" />
    </div>
    <div class="flex justify-end items-center mt-2">
      <div class="flex">
        <a-button type="default" class="mr-4" @click="onCancel">取消</a-button>
        <a-button type="primary" @click="onOk"> 确定 </a-button>
      </div>
    </div>
    <Refund v-model:open="priceOpen" :vip-price="vipPrice" :business-data="{ ...cancelInfo }" :loading-state="loadingState" @success="onSuccessPrice" />
  </a-modal>
</template>
<script setup>
import { ref, watch } from 'vue'
import { message } from 'ant-design-vue'
import { post } from '@/utils/request'
import useUserStore from '@/store/user'
import { getSystemConfig } from '@/utils/systemConfig'
import AccountQuerySix from '@/components/ReadCard/AccountQuerySix'
import AccountQueryFive from '@/components/ReadCard/AccountQueryFive'
import Refund from '../../../components/RefundModal.vue'

const { empId } = useUserStore()
const emit = defineEmits(['update:open', 'success'])
const props = defineProps({
  open: Boolean,
  patientInfo: {
    type: Object,
    default: () => ({})
  },
  actionType: {
    type: Number,
    default: 0 // 0: 医保登记 1: 医保退号
  },
  searchParams: {
    type: Object,
    default: () => ({})
  }
})
const formState = ref({ dpJe: '' })
const accountQueryData = ref({})
const checkInsutypeName = ref({}) //选中的险种类别
const payType = ref([])
// const payment = ref(null)
const loginUserDepartment = ref({})
const tabActiveKey = ref('社保卡')
const readCardSettingStr = ref('') //调用壳使用的json
const jsonStr = ref('')
const accountQueryFiveOpen = ref(false)
const accountQuerySixOpen = ref(false)
const isSixSelect = ref({})
const inAreaCode = ref('00') //00:国家医保101:上海医保 默认为 00
const priceOpen = ref(false)
const cardTypeEnum = {
  社保卡: {
    mdtrtCertType: '03',
    area: '*'
  },
  身份证: {
    mdtrtCertType: '02',
    area: '*'
  },
  电子凭证: {
    mdtrtCertType: '01',
    area: '*'
  },
  刷脸授权: {
    mdtrtCertType: '01',
    area: '00'
  },
  终端扫码: {
    mdtrtCertType: '01',
    area: '00'
  },
  磁卡: {
    mdtrtCertType: '00',
    area: '01'
  },
  特殊人员: {
    mdtrtCertType: '06',
    area: '01'
  }
}

//获取付费方式
const getPayTypeData = async () => {
  const { code, data, msg } = await post('/operation/opex/getDictCommonItemList', {
    dictCommonCode: 'DT00289',
    status: 1
  })
  if (code !== 0) return message.error(msg || '获取付费方式失败')
  payType.value = data
  if (payType.value && payType.value.length > 0) {
    const payType = data.filter((item) => {
      return item.dictItemName === '城乡居民基本医疗保险'
    })
    if (payType && payType.length > 0) {
      medFormState.value.payment = payType[0].dictItemCode
    }
  }
}

// 医保切换
const onTabRadioChange = async (e) => {
  let businessType = 0
  if (e.target.value === '社保卡' || e.target.value === '身份证') {
    businessType = 1
  } else if (['电子凭证', '刷脸授权', '终端扫码'].includes(tabActiveKey.value)) {
    businessType = '01101'
  } else if (e.target.value === '磁卡') {
    businessType = '00'
  }
  const res = await post('/outp/mzdj/getMedicareCardSettinglnfo', { businessType, officeid: loginUserDepartment.value.ksdm })
  if (res.code !== 0) return message.error(res.msg)
  readCardSettingStr.value = res.data
}

const medFormState = ref({})
const isGb = ref(true) //false 五期 true 国平
const idNumber = ref('')
//读取社保卡/身份证/电子凭证
const readYbSrzCard = async (flag = false) => {
  let res = {}
  if (flag) {
    //无身份证识别
    if (!idNumber.value) return message.error('请输入身份证号')
    res = await post('/outp/mzdj/getReadPatientInfo', {
      type: 'YBDJ',
      brName: '',
      brSfz: idNumber.value
    })
  } else {
    if (tabActiveKey.value === '社保卡') {
      jsonStr.value = window.openExe?.readYBK(readCardSettingStr.value) //社保卡
    } else if (tabActiveKey.value === '身份证') {
      jsonStr.value = window.openExe?.readSFZ(readCardSettingStr.value) //身份证
    } else if (tabActiveKey.value === '磁卡') {
      jsonStr.value = window.openExe?.readCK(formState.value.ck, readCardSettingStr.value) //调用壳
    } else if (tabActiveKey.value === '电子凭证') {
      jsonStr.value = window.openExe?.readDZPZ(formState.value.ck, readCardSettingStr.value) //电子凭证
    } else if (tabActiveKey.value === '刷脸授权' || tabActiveKey.value === '终端扫码') {
      const params = JSON.parse(readCardSettingStr.value)
      const paramsJson = JSON.stringify({
        ...params,
        fficeid: loginUserDepartment.value.ksdm,
        officename: loginUserDepartment.value.ksmc,
        slurl: getSystemConfig('FACE_SWIPING_URL')
      })
      jsonStr.value = tabActiveKey.value === '刷脸授权' ? window.openExe?.readSL(paramsJson) : window.openExe?.readSLSM(paramsJson) //刷脸
    }
    if (!window.openExe) {
      jsonStr.value =
        '{"ksbm_new":null,"jzpzbh_1101":"320000ecd15n606u7e82223a0a0000b154fcc7","jzpzbh":"320000ecd15n606u7e82223a0a0000b154fcc7","ksbm":"A10","name":"张一凡","zjhm":"41282619990109251X","br_id":"41282619990109251X","shbzkh":"41282619990109251X","cbdqh":null,"hatm_empid":"ZZGH","hatm_zdh":"ZZGH001"}'
    }
    res = await post('/outp/mzdj/getReadPatientInfo', {
      jsonStr: jsonStr.value,
      mdtrtCertNo: '',
      mdtrtCertType: cardTypeEnum[tabActiveKey.value].mdtrtCertType
    })
  }
  if (res.code !== 0) return message.error(res.msg || '读卡失败')
  if (!res.data.ybkResonse?.br_id) return message.error('无病人信息')
  if (res.data.ybkResonse?.xm !== formState.value.brName && props.actionType === 0) return message.error('医保患者姓名与当前补登记的姓名不一致，禁止补登记')
  if (res.data.ybkResonse?.xm !== formState.value.brName && props.actionType === 1) {
    return message.error('医保患者姓名与当前退号患者的姓名不一致，禁止退号')
  }
  isGb.value = res.data.isgb
  accountQueryData.value = res.data || {}
  medFormState.value = { ck: formState.value.ck, ...res.data, ...res.data.baseinfo } || {}
  medFormState.value.insureNo = res.data.ybkResonse?.kh
  medFormState.value.ksbm_new = res.data.ybkResonse?.ksbm_new
  medFormState.value.insuplc_admdvs = res.data.ybkResonse?.insuplc_admdvs
  // 0: 医保登记 1: 医保退号
  if (props.actionType === 0) {
    if (res.data.yxinsuinfo && res.data.yxinsuinfo.length === 1) {
      //如果有有效险种类别并且只有一个，默认取第一个
      checkInsutypeName.value = JSON.parse(JSON.stringify(res.data.yxinsuinfo[0])) //赋值一个险种类别
    }
    if (res.data.yxinsuinfo && res.data.yxinsuinfo.length > 1) {
      if (isGb.value) {
        // 国平
        accountQuerySixOpen.value = true
      } else {
        //五期
        accountQueryFiveOpen.value = true
      }
    }
    if (!res.data.yxinsuinfo) {
      //没有的话就取所有险种类别第一个
      if (res.data.insuinfo && res.data.insuinfo.length > 0) {
        checkInsutypeName.value = JSON.parse(JSON.stringify(res.data.insuinfo[0]))
      } else {
        checkInsutypeName.value = {}
      }
    }
  }
}

// 险种类别
const onClickInsutypeName = (val) => {
  openAccountQueryModal()
  isSixSelect.value = val
}

const openAccountQueryModal = () => {
  if (!medFormState.value.insureNo) {
    if (tabActiveKey.value === '社保卡') return message.warning('请先读取社保卡')
    if (tabActiveKey.value === '身份证') return message.warning('请先读取身份证')
    if (tabActiveKey.value === '电子凭证') return message.warning('请先扫描电子凭证')
    if (tabActiveKey.value === '刷脸授权') return message.warning('请先读取刷脸授权')
    if (tabActiveKey.value === '终端扫码') return message.warning('请先读取终端扫码')
  }
  if (isGb.value) {
    // 国平
    accountQuerySixOpen.value = true
  } else {
    //五期
    accountQueryFiveOpen.value = true
  }
}

// 选择险种类别
const onSelectCHS = (row) => {
  checkInsutypeName.value.insutype = row.insutype
  checkInsutypeName.value.insutypeName = row.insutypeName
  checkInsutypeName.value.insuplc_admdvs = row.insuplc_admdvs
}
const cancelInfo = ref({})
const changeType = ref('')
const chargeTitle = ref('')
const vipPrice = ref(0)
const onOk = async () => {
  if (!formState.value?.med_type) return message.error('请选择医疗类别')
  const params = {
    inplsh: formState.value.inplsh,
    insutype: checkInsutypeName.value.insutype, // 险种类型
    mdtrtCertNo: medFormState.value?.mdtrtCertNo, // 就诊凭证编号 磁卡：传卡内数据 电子凭证：传ecToken 身份证：不传 医保卡：传身份证号
    mdtrtCertType: medFormState.value.mdtrtCertType,
    med_type: formState.value.med_type, // 医疗类别 Y
    ybkh: medFormState.value?.insureNo, // 人员编号
    brSfz: medFormState.value?.sfzh,
    zhbs: medFormState.value?.zhbs
  }
  // 0: 医保登记 1: 医保退号
  if (props.actionType === 0) {
    getMedical(params)
  } else {
    vipPrice.value = props.patientInfo.vipzf || 0
    const { code, msg, data } = await post('/outp/mzdj/doCancel', { jzbh: props.patientInfo.jzbh, yybh: props.patientInfo.yybh, type: '1' })
    if (code !== 0) message.error(msg || '退号失败')
    if (data) {
      cancelInfo.value = data || {}
      if (data.sjdj) {
        changeType.value = 'yb'
        chargeTitle.value = `原收费${formatMoney(props.patientInfo.zfy)}  |  医保支付${formatMoney(props.patientInfo.ybje)}  分币￥${
          props.patientInfo.fbyh
        }  原收费流水号 ${props.patientInfo.yblsh}`
        priceOpen.value = true
      } else {
        const { code, data } = await post('/outp/oupCharge/getChargeTypeList')
        if (code !== 0) return
        const chargeData = {}
        if (data && data.length > 0) {
          data.forEach((item) => {
            chargeData[item.zffsdm] = chargeData[item.zffsdm] ? chargeData[item.zffsdm] : 0
          })
        }
        chargeData.change = 0
        chargeData.fbyh = 0
        chargeData.yhje = 0
        chargeData.ysje = '0.00'
        chargeData.ssje = '0.00'
        onSuccessPrice(chargeData)
      }
    } else {
      message.success(msg)
    }
  }
}

const getMedical = async (params) => {
  const parameter = {
    brId: formState.value.brId,
    baseinfo: accountQueryData.value.baseinfo,
    ybkResonse: accountQueryData.value.ybkResonse
  }
  const res = await post('/common/patient/doSaveMedicalInsuranceInformation', parameter)
  if (res.code !== 0) return message.error(res.msg)
  const parameterTwo = {
    brId: formState.value.brId,
    ...accountQueryData.value,
    ...params
  }
  if (isGb.value) {
    const resTwo = await post('/outp/mzdj/doSaveYbBrxx', parameterTwo)
    if (resTwo.code !== 0) return message.error(resTwo.msg)
    if (res && resTwo) {
      const parameterThree = {
        jzbh: formState.value.jzbh,
        ...params
      }
      const resThree = await post('/outp/mzdj/doMedicalInsuranceRegistrationSupplement', parameterThree)
      if (resThree.code !== 0) return message.error(resThree.msg)
      message.success('保存成功')
      emit('success')
      onCancel()
    }
  } else {
    const parameterThree = {
      jzbh: formState.value.jzbh,
      ...params
    }
    const resThree = await post('/outp/mzdj/doMedicalInsuranceRegistrationSupplement', parameterThree)
    if (resThree.code !== 0) return message.error(resThree.msg)
    message.success('保存成功')
    emit('success')
    onCancel()
  }
}
const loadingState = ref(false)
const onSuccessPrice = async (params) => {
  //阜阳医保才会调壳验证密码
  let verRes = ''
  if (getSystemConfig('NMI_REGION_CODE') === '022' && checkInsutypeName.value.insutype === '310' && tabActiveKey.value === '社保卡') {
    verRes = await window.openExe?.iVerifyPIN()
  }
  const res = await post(
    'outp/mzdj/medicalInsuranceRefundNumber',
    {
      jzbh: props.patientInfo.jzbh,
      fphm: cancelInfo.value.pjhm,
      kh: medFormState.value.kh,
      mdtrtCertNo: medFormState.value.mdtrtCertNo,
      mdtrtCertType: medFormState.value.mdtrtCertType,
      tftype: 'GH',
      type: '1',
      mmJson: verRes ? verRes : undefined
    },
    {
      loadingState: true
    }
  )
  if (res.code !== 0) return message.error(res.msg || '退号失败')
  if (medFormState.value.isgb) {
    const { code, msg } = await post(
      'outp/oupCharge/doSaveNMlOutPRefund',
      {
        pjhm: cancelInfo.value.pjhm,
        yylsh: cancelInfo.value.yylsh,
        ...params,
        tflx: cancelInfo.value.tflx,
        lshs: cancelInfo.value.dtlsh,
        newpjhm: res.data.pjhm,
        type: '1'
      },
      {
        loadingState: true
      }
    )
    if (code !== 0) return message.error(msg)
    priceOpen.value = false
    message.success(msg || '退号成功')
    emit('success')
    onCancel()
  } else {
    let result = window.openExe?.readGHQQ(res.data)
    if (!window.openExe) {
      result =
        '{"response":{"czybm":"0000","sysResv":"1234567887654321Ti8ri8rTT8ir8rTiriT8TTir8Trrii8r8Tirc0a8006e","recvTime":"0004089798fc01d6","bbh":"0001","msgid":"9999999870020211229000824890","fhxx":"","jyqd":"10","xxlxm":"SK01","jyyzm":"","xzqhdm":"310000","jysj":"2021-12-29 11:16:38","jgdm":"99999998700","xxfhm":"P001","zdsbsbm":"","czyxm":"系统管理员","xxnr":{"translsh":"2101010287593929","zfcash":"5","dffj":"0.00","curaccountamt":"0.00","curaccount":"0.00","tc":"0.00","tccash":"0.00","dffjhisaccount":"0.00","cardid":"N02423258","accountattr":"1000000000000000","tchisaccount":"0.00","hisaccount":"0.00","dffjcash":"0.00","cardtype":"1","hisaccountamt":"0.00","personname":"测试卡0800"}}}'
    }
    const res1 = await post('outp/mzdj/doCallbackAPi', {
      jsonStr: result,
      jzbh: props.patientInfo.jzbh,
      pjhm: cancelInfo.value.pjhm
    })
    if (res1.code !== 0) return message.error(res1.msg || '退号失败')
    const { code, msg } = await post('outp/oupCharge/doSaveNMlOutPRefund', {
      pjhm: cancelInfo.value.pjhm,
      yylsh: cancelInfo.value.yylsh,
      ...params,
      tflx: cancelInfo.value.tflx,
      lshs: cancelInfo.value.dtlsh,
      newpjhm: res.data.pjhm,
      type: '1'
    })
    if (code !== 0) return message.error(msg)
    priceOpen.value = false
    message.success(msg || '退号成功')
    emit('success')
    onCancel()
  }
}
const getLoginUserDepartment = async () => {
  const res = await post('/common/masterData/getByYsbhDepartment', { empId: empId })
  if (res.code !== 0) message.error(res.msg || '获取登录人科室失败')
  loginUserDepartment.value = res?.data || {}
}

const onCancel = () => {
  emit('update:open', false)
}
const formatMoney = (val) => {
  if (val) {
    return '￥' + formatAmount(val)
  } else {
    return '￥' + '0.00'
  }
}

watch(
  () => props.open,
  (val) => {
    if (val) {
      getPayTypeData()
      formState.value = props.patientInfo
      checkInsutypeName.value.insutype = props.patientInfo?.insutype
      checkInsutypeName.value.insutypeName = props.patientInfo?.insutypeName
      idNumber.value = props.patientInfo?.brSfz
    } else {
      medFormState.value = {}
      formState.value = {}
      checkInsutypeName.value = {}
      tabActiveKey.value = '社保卡'
      idNumber.value = ''
    }
  },
  { immediate: true }
)
const filterType = () => {
  // area为01为上海五期医保单独处理  其余按国家医保处理
  if (inAreaCode.value) {
    const tab = []
    for (const key in cardTypeEnum) {
      if (Object.hasOwnProperty.call(cardTypeEnum, key)) {
        const element = cardTypeEnum[key]
        if (inAreaCode.value === '01') {
          if (element.area === '01' || element.area === '*') {
            element.name = key
            tab.push(element)
          }
        } else {
          if (element.area === '00' || element.area === '*') {
            element.name = key
            tab.push(element)
          }
        }
      }
    }
    return tab
  } else {
    message.error('请联系管理员设置医保区域代码')
    return []
  }
}
onMounted(() => {
  inAreaCode.value = getSystemConfig('NMI_REGION_CODE') //00:国家医保101:上海医保 默认为 00
  getLoginUserDepartment()
})
</script>

<style lang="less" scoped>
.ant-tag-checkable-checked {
  color: #fff;
  background-color: var(--primary-color);
}
</style>
